﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Workflow.Common.ExcelHelp;
using Workflow.Common.Tools;
using Workflow.Dto;
using Workflow.IService;
using Workflow.Model;
using Workflow.Resource;
using Workflow.Service;
using Workflow.Web.Common;

namespace Workflow.Web.Controllers
{
	[Localization]
	[UserAuthorize]
	public class UserController : Controller
	{
		//
		// GET: /UserManager/

		public IUserManager UserManager { get; set; }
		public IGroupService GroupService { get; set; }
		public IRoleService RoleService { get; set; }
		public IApplicatService ApplicatService { get; set; }

		

		public ActionResult Index()
		{
			return View();
		}
		public ActionResult GetUser()
		{
			string s = Request["page"] ?? "1";
			string r = Request["rows"];
			string sortfield = Request["sort"];
			string order = Request["order"];
			if (sortfield == null)
				sortfield = "InvoiceNo";
			if (r == null)
				r = "20";
			long count;
			var userID = Request["UserID"];
			var userName = Request["UserName"];
			var group = Request["Group"];


			UserQueryDto userQueryDto = new UserQueryDto();
			long id;
			if (Int64.TryParse(userID, out id))
			{
				userQueryDto.UserID = id;
			}

			userQueryDto.UserName = userName;
			userQueryDto.UserGroupCode = group;

			var users = UserManager.GetUsersByPage(out count, int.Parse(s), int.Parse(r), userQueryDto);

			var list = users.Select(entity => new
		  {
			  entity.UserID,
			  entity.UserName,
			  entity.Email,
			  entity.GroupId.GroupName,
			  entity.IsValid,
			  RoleName = entity.RoleId ==null? null:entity.RoleId.RoleName
		  });

			var result = new { total = count, rows = list.ToList() };


			return this.Json(result, JsonRequestBehavior.AllowGet);

		}
		public ActionResult Supplier()
		{
			return View();
		}
		public ActionResult Detail(string id)
		{
			User entity = null;
			if (id != null)
			{
				entity = this.UserManager.GetUser(Int64.Parse(id));
			}
			entity = entity ?? new User()
								{
									UserName = string.Empty,
									Email = string.Empty,
									Password = String.Empty,
									RoleId = null,
									GroupId = null

								};

			this.ViewData["entity"] = entity;
			return View();
		}
		public ActionResult GetGroup()
		{

			var date = GroupService.GetAllGroups();


			return Json(date, "text/plain", JsonRequestBehavior.AllowGet);
		}
		public ActionResult GetRole()
		{
			var groupCode = Request["id"];
			var date = RoleService.GetRolesForGroup(int.Parse(groupCode));


			return Json(date, "text/plain", JsonRequestBehavior.AllowGet);
		}
		public ActionResult GetGroupList()
		{

			var date = GroupService.GetAllGroups();

			date.Insert(0, new Group() { GroupCode = 0, GroupName = Global.pleaseSelect });

			return Json(date, "text/plain", JsonRequestBehavior.AllowGet);
		}

		public ActionResult SaveUser(User entity, string Group, string Role ,string NextStepUser)
		{
			try
			{
				if (entity.UserID==0)
				{

					//entity.UserID = GetUserID();
					var group = this.GroupService.GetGroup(int.Parse(Group));
					Role role = null;
					if (!string.IsNullOrEmpty(Role))
					{
						role = this.RoleService.GetRole(int.Parse(Role));
					}
					entity.GroupId = group;
					entity.RoleId = role;
					entity.CreateTime = ToolsHelper.GetTimeZoneNow();
					entity.Password = "000000";
					entity.IsValid = true;
					if (!string.IsNullOrEmpty(NextStepUser))
					{
						var nextUser = this.UserManager.GetUser(Int64.Parse(NextStepUser));
						entity.NextStepUser = nextUser;
					}
					else
					{
						entity.NextStepUser = null;
					}
					this.UserManager.SaveOrUpdateUser(entity);
				}
				else
				{
					var model = this.UserManager.GetUser(entity.UserID);
					var group = this.GroupService.GetGroup(int.Parse(Group));
					Role role = null;
					if (!string.IsNullOrEmpty(Role))
					{
						role = this.RoleService.GetRole(int.Parse(Role));
					}
					entity.RoleId = role;
					if (!string.IsNullOrEmpty(NextStepUser))
					{
						var nextUser = this.UserManager.GetUser(Int64.Parse(NextStepUser));
						model.NextStepUser = nextUser;
					}
					else
					{
						model.NextStepUser = null;
					}
					model.GroupId = group;
					model.RoleId = role;
					model.Email = entity.Email;
					model.UserName = entity.UserName;
					
					this.UserManager.SaveOrUpdateUser(model);
				}

				return Json(new { Success = true, Message = Global.SaveSuccess }, "text/html", JsonRequestBehavior.AllowGet);

			}
			catch (Exception ex)
			{
				return Json(new { Success = false, Message = Global.SaveFalse }, "text/html", JsonRequestBehavior.AllowGet);

			}


		}

		public ActionResult DeleteUser(string id)
		{
			try
			{
				if (!string.IsNullOrEmpty(id))
				{


					this.UserManager.DeleteUser(id);
				}

				return Json(new { Success = true, Message = Global.ActiveSuccess }, "text/html", JsonRequestBehavior.AllowGet);
			}
			catch (Exception ex)
			{
				return Json(new { Success = false, Message = Global.SaveFalse }, "text/html", JsonRequestBehavior.AllowGet);

			}
		}
		public ActionResult ActiveUser(string id)
		{
			try
			{
				if (!string.IsNullOrEmpty(id))
				{

					var model = this.UserManager.GetUser(Int64.Parse(id));
					model.IsValid = !model.IsValid;
					UserManager.SaveOrUpdateUser(model);
				}

				return Json(new { Success = true, Message = Global.ActiveSuccess }, "text/html", JsonRequestBehavior.AllowGet);
			}
			catch (Exception ex)
			{
				return Json(new { Success = false, Message = Global.SaveFalse }, "text/html", JsonRequestBehavior.AllowGet);

			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		private static string GetUserID()
		{
			Random r = new Random();
			return "G" + r.Next(9999999);
		}

		public ActionResult EditPassword()
		{
			var id = Request["id"];
			var password = Request["newpass"];
			try
			{
				if (!string.IsNullOrEmpty(id))
				{

					var model = this.UserManager.GetUser(Int64.Parse(id));
					model.Password = password;
					UserManager.SaveOrUpdateUser(model);
				}

				return Json(new { Success = true, Message = Global.ActiveSuccess }, "text/html", JsonRequestBehavior.AllowGet);
			}
			catch (Exception ex)
			{
				return Json(new { Success = false, Message = Global.SaveFalse }, "text/html", JsonRequestBehavior.AllowGet);

			}
		}
		public ActionResult EditPasswordForCurrentUser()
		{
			var id = Session[ConfigReader.AuthorizeSessionUserID].ToString();
			var password = Request["newpass"];
			try
			{
				if (!string.IsNullOrEmpty(id))
				{

					var model = this.UserManager.GetUser(Int64.Parse(id));
					model.Password = password;
					UserManager.SaveOrUpdateUser(model);
				}

				return Json(new { Success = true, Message = Global.ActiveSuccess }, "text/html", JsonRequestBehavior.AllowGet);
			}
			catch (Exception ex)
			{
				return Json(new { Success = false, Message = Global.SaveFalse }, "text/html", JsonRequestBehavior.AllowGet);

			}
		}
		public ActionResult GetUserList()
		{
			var role =Request["id"];
			int roleId;
			int.TryParse(role, out roleId);
			var date = UserManager.GetUserForRole(roleId);

			date.Insert(0, new User() { UserID = 0, UserName = Global.pleaseSelect });

			var rusalt = date.Select(
				x => new
				{
					x.UserID,
					x.UserName

				});
		
			return Json(rusalt, "text/plain", JsonRequestBehavior.AllowGet);
		}

		public static bool HasFile(HttpPostedFileBase file)
		{
			return (file != null && file.ContentLength > 0) ? true : false;
		}
		[HttpPost]
		public ActionResult UploadFile()
		{
			try
			{
				foreach (string upload in Request.Files)
				{
					if (!HasFile(Request.Files[upload])) continue;
					string path = AppDomain.CurrentDomain.BaseDirectory + "TempFiles/";
					string filename = Path.GetFileName(Request.Files[upload].FileName);

					Request.Files[upload].SaveAs(Path.Combine(path, filename));


					DataTable dt = ExcelHelper.ImportFromExcel(Path.Combine(path, filename));

					ApplicatService.SaveApplicatList(dt);

					System.IO.File.Delete(Path.Combine(path, filename));
				}

				return Json(new { Success = true, Message = Global.UploadSuccess }, "text/html", JsonRequestBehavior.AllowGet);
			}
			catch (Exception ex)
			{
				return Json(new { Success = false, Message = Global.UploadFail }, "text/html", JsonRequestBehavior.AllowGet);

			}
		}

		
	}
}
